package org.kumas.sgrpc.remoting.transport.netty;


import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

import com.sun.jndi.toolkit.url.UrlUtil;

import org.kumas.sgrpc.common.URL;
import org.kumas.sgrpc.common.constants.CommonConstants;
import org.kumas.sgrpc.common.extension.ExtensionLoader;
import org.kumas.sgrpc.common.utils.ExecutorUtil;
import org.kumas.sgrpc.common.utils.NetUtils;
import org.kumas.sgrpc.remoting.Channel;
import org.kumas.sgrpc.remoting.ChannelHandler;
import org.kumas.sgrpc.remoting.Codec;
import org.kumas.sgrpc.remoting.Constants;
import org.kumas.sgrpc.remoting.RemotingException;
import org.kumas.sgrpc.remoting.RemotingServer;
import org.kumas.sgrpc.remoting.transport.AbstractServer;
import org.kumas.sgrpc.remoting.transport.dispatcher.ChannelHandlers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.DefaultThreadFactory;
import static org.kumas.sgrpc.common.constants.CommonConstants.KEEP_ALIVE_KEY;
import static org.kumas.sgrpc.common.constants.CommonConstants.TIMEOUT_KEY;

/**
 * @author KumasZhang
 * @version 1.0
 * @since 2021-07-15 08:12
 */
public class NettyServer extends AbstractServer implements RemotingServer {
    private static final Logger logger = LoggerFactory.getLogger(NettyServer.class);
    private Map<String, Channel> channels;
    private ServerBootstrap bootstrap;
    private io.netty.channel.Channel channel;
    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;

    public NettyServer(URL url,
        ChannelHandler handler) throws RemotingException {
        super(ExecutorUtil.setThreadName(url, SERVER_THREAD_POOL_NAME),  ChannelHandlers.wrap(handler, url));
    }

    @Override
    protected void doOpen() throws Throwable {
        bootstrap = new ServerBootstrap();
        ThreadFactory bossThreadFactory = new DefaultThreadFactory("NettyServerBoss", true);
        bossGroup = new NioEventLoopGroup(1, bossThreadFactory);

        ThreadFactory workerThreadFactory = new DefaultThreadFactory("NettyServerWorker", true);
        workerGroup = new NioEventLoopGroup(getUrl().getPositiveParameter(CommonConstants.IO_THREADS_KEY,
            Constants.DEFAULT_IO_THREADS), workerThreadFactory);

        final NettyServerHandler nettyServerHandler = new NettyServerHandler(getUrl(), this);
        channels = nettyServerHandler.getChannels();

        boolean keepalive = getUrl().getParameter(KEEP_ALIVE_KEY, Boolean.FALSE);

        bootstrap.group(bossGroup, workerGroup)
            .channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_REUSEADDR, Boolean.TRUE)
            .childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    int idleTimeout = getUrl().getParameter(Constants.HEARTBEAT_KEY, Constants.DEFAULT_HEARTBEAT);

                    NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyServer.this);
                    //未添加ssl支持
                    socketChannel.pipeline()
                        .addLast("decoder", adapter.getDecoder())
                        .addLast("encoder",adapter.getEncoder())
                        .addLast("server-idle-handler", new IdleStateHandler(0, 0, idleTimeout, TimeUnit.MILLISECONDS))
                        .addLast("handler", nettyServerHandler);
                }
            });
        ChannelFuture channelFuture = bootstrap.bind(getBindAddress());

        channelFuture.syncUninterruptibly();
        channel = channelFuture.channel();
    }

    @Override
    protected void doClose() throws Throwable {
        try {
            if (channel != null) {
                channel.close();
            }
        } catch (Throwable e) {
            logger.warn(e.getMessage(), e);
        }

        try {
            Collection<Channel> channels = getChannels();
            if (channels != null && channels.size() > 0) {
                for (Channel channel : channels) {
                    try {
                        channel.close();
                    } catch (Throwable e) {
                        logger.warn(e.getMessage(), e);
                    }
                }
            }
        } catch (Throwable e) {
            logger.warn(e.getMessage(), e);
        }

        try {
            if (bootstrap != null) {
                bossGroup.shutdownGracefully().syncUninterruptibly();
                workerGroup.shutdownGracefully().syncUninterruptibly();
            }
        } catch (Throwable e) {
            logger.warn(e.getMessage(), e);
        }

        try {
            if (channels != null) {
                channels.clear();
            }
        } catch (Throwable e) {
            logger.warn(e.getMessage(), e);
        }
    }

    @Override
    public boolean isBound() {
        return channel.isActive();
    }

    @Override
    public Collection<Channel> getChannels() {
        Collection<Channel> chs = new ArrayList<>(this.channels.size());
        chs.addAll(this.channels.values());

        return chs;
    }

    @Override
    public Channel getChannel(InetSocketAddress remoteAddress) {
        return channels.get(NetUtils.toAddressString(remoteAddress));
    }
}
